package jdbc.day;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

public class DemoOne {
    public static void main(String[] args) throws Exception {
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        //获取连接对象
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, user, password);

        //获取SQL语句的对象
//        Statement statement = connection.createStatement();
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT id,name,age,gender,money FROM tb_user WHERE name = ?");

        //sql注入
        System.out.println("请输入name:");
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        //编写SQL语句,接受返回的结果集
//        String sql = "SELECT id,name,gender FROM tb_user";
//        String sql = "SELECT id,name,gender FROM tb_user WHERE name = '" + name + "'";//abc' or '1' = '1
//        ResultSet resultSet = statement.executeQuery(sql);
        //为？占位符赋值
        preparedStatement.setString(1, name);
        ResultSet resultSet = preparedStatement.executeQuery();

        //打印结果
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name1 = resultSet.getString("name");
            int age = resultSet.getInt("age");
            String gender = resultSet.getString("gender");
            String phone = resultSet.getString("money");
            System.out.println(id + "\t " + name1 + "\t " + age + " \t" + gender+ "\t" + phone);
        }

        //释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
        System.out.println("ok");
    }
}
